package com.kfm.service.impl;

import com.kfm.dao.SysUserRepository;
import com.kfm.domain.SysUser;
import com.kfm.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.Set;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    /**
     * 根据用户名获取用户信息
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 用户名不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserRepository.findByUsername(username);
        if (ObjectUtils.isEmpty(sysUser)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // TODO 此处应该将该用户权限查询出来, 我们后续再改造，现在先默认
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();

        // 设置角色权限, ROLE_ 为Spring Security默认的角色前缀
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        // 设置资源权限
        authorities.add(new SimpleGrantedAuthority("sys:user:add"));

        sysUser.setAuthorities(authorities);
        return sysUser;
    }
}
